var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var ordersRouter = require('./routes/orders');
var productsRouter = require('./routes/products');
var cartRouter = require('./routes/carts');
var addAddressRouter = require('./routes/address');

var passport = require('passport')    //1.导入认证模块

var app = express();
app.use(passport.initialize())      //2.使用认证模块
//3.配置认证鉴权策略
var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'mykey'; //和生成token时sign函数的参数保持一致
//4.配置验证token的方法
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    //jwt_payload是生成token时保存的用户对象
    return done(null, jwt_payload);    //表示token验证通过
}));

app.all("*",function(req,res,next){
  // 设置允许跨域的域名,*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin','*');
  // 允许的header类型
  res.header('Access-Control-Allow-Headers','*');
  // 跨域允许的请求方式
  res.header('Access-Control-Allow-Methods','DELETE,PUT,POST,GET,OPTIONS');
  if(req.method.toLowerCase() == 'options')
      res.send(200); // 让options 尝试请求快速结束
  else
      next();
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/api', usersRouter);
app.use('/api', ordersRouter);
app.use('/api', productsRouter);
app.use('/api', cartRouter);
app.use('/api',addAddressRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;